package com.hava.eb.service;

import com.hava.eb.entity.Product;
import com.hava.eb.entity.User;
import com.hava.eb.repository.Op;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * Created by yanfa on 2016/10/9.
 */
public class SelectMyBatis {

    public static void main(String[] args) {
        // 1. 声明配置⽂件的⺫录渎职
        String resource = "mybatis-conf.xml";
        // 2. 加载应⽤配置⽂件
        InputStream is = SelectMyBatis.class.getClassLoader()
                .getResourceAsStream(resource);
        // 3. 创建SqlSessonFactory
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
                .build(is);
        // 4. 获取Session
        SqlSession session = sessionFactory.openSession();
        try {
            // 5. 获取操作类
            Op op = session.getMapper(Op.class);
            // 6. 完成查询操作

            // get product
            Product product = op.getProduct(1);
            System.out.println("[product.id]:" + product.getId() + " [product.productName]:" + product.getProductName() + " [product.catalog]:" + product.getCatalog());

            // get user
            User user = op.getUser(1);
            System.out.println("[user.id]:" + user.getId() + " [user.userName]:" + user.getUserName() + " [user.tel]:" + user.getTel());
            for(int product_id : user.getProducts())
                System.out.println("    [product_id]:" + product_id);
        } finally {
            // 7.关闭Session
            session.close();
        }
    }
}
